package dnet

import (
	"dgo/goutils/utils"
	"net"
	"sync/atomic"
)

/*
*

	只開放一個端口
*/
type DNetFtpServ struct {
	onlinecnt      int32
	listener       *NetListener
	onlinelst      utils.GSyncMapGroup
	OnAuthEvent    func(cmd *FtpCmdRequest) bool
	OnExecCMDEvent func(cmd *FtpCmdRequest) bool
}

func NewDNetFtpServ() *DNetFtpServ {
	rval := &DNetFtpServ{
		listener: NewNetListener(),
	}
	rval.init()
	return rval
}

func (this *DNetFtpServ) init() {
	this.listener.OnListenSucc = func(network, addr string) {

	}
	this.listener.HandleConnFunc = this.onHandleConn
}

func (this *DNetFtpServ) ConfigAddr(addr string) {
	this.listener.Config("tcp", addr)
}

func (this *DNetFtpServ) Start() {
	this.listener.CheckStart()
}

func (this *DNetFtpServ) innerHandleConnFunc(conn net.Conn) {
	if utils.GoFunCatchException {
		defer utils.PanicHandler()
	}

	handler := NewServConnHandler(this, conn)
	this.onlinelst.Set(handler, handler)
	atomic.AddInt32(&this.onlinecnt, 1)
	defer func() {
		atomic.AddInt32(&this.onlinecnt, -1)
		this.onlinelst.Remove(handler)
	}()

	handler.clientHandleEntry()
}

func (this *DNetFtpServ) onHandleConn(conn net.Conn) {
	go this.innerHandleConnFunc(conn)
}
